package vn.lumi.smarthome.ui;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Scene.OnControlSceneListener;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.DeviceFragment.DeviceReceiver;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SceneFragment extends BaseFragment implements
		LoaderCallbacks<Cursor>, OnControlSceneListener {
	private static final String TAG = "SceneFragment";

	private ListView mListScenes;
	private SceneAdapter mSceneAdapter;

	ProgressDialog progressDialog;
	SceneReceiver mReceiver;
	private static SceneFragment mSceneFragment;
	// Khai bao ID cua Loader
	private static final int LOADER_ID = 1;

	public SceneFragment() {
		LogUltis.i(TAG, "create SceneFragment");
	}

	public static SceneFragment newInstance(int floor_id, int room_id) {
		if (mSceneFragment == null) {
			mSceneFragment = new SceneFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		mSceneFragment.setArguments(bundle);
		return mSceneFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_scene, container, false);
		init_view(view);

		return view;
	}

	private void init_view(View view) {
		mListScenes = (ListView) view
				.findViewById(R.id.fragment_scene_list_scene);

		mSceneAdapter = new SceneAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mSceneAdapter.initData(mFloor_id, mRoom_id);
		mSceneAdapter.setControlScene(this);
		mListScenes.setAdapter(mSceneAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		// load data
		refreshData(mFloor_id, mRoom_id);
		// kiem tra xem co cho rung khong
		Config.isVibrate = Preference.getVibrate(getActivity());
		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet
																				// lap
		// ngon ngu
	}

	@Override
	public void refreshData(int floor_id, int room_id) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
		mSceneAdapter.refreshData(floor_id, room_id);
		mSceneAdapter.swapCursor(null);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		int room_id = bundle.getInt(ROOM_ID);
		String selection = TBL_Scene.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		return new CursorLoader(getActivity(), TBL_Scene.CONTENT_URI_SCENE,
				null, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mSceneAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mSceneAdapter.swapCursor(null);
	}

	private class SceneAdapter extends CursorAdapter {
		Context mContext;
		int floor_id = 0;
		int room_id = 0;

		private static final String TAG = "SceneAdapter";

		private OnControlSceneListener mOnControlSceneListener;

		public SceneAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			mContext = context;
		}

		public void initData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		public void refreshData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		public void setControlScene(
				OnControlSceneListener onControlSceneListener) {
			this.mOnControlSceneListener = onControlSceneListener;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
			final TextView txtName = (TextView) view
					.findViewById(R.id.item_listview_scene_active_txt_name);
			TextView txvSchedule = (TextView) view
					.findViewById(R.id.item_listview_scene_activie_txv_schedule);
			// ImageView imgConfig = (ImageView)
			// view.findViewById(R.id.item_listview_schedule_active_img_config);

			// set name
			final String sceneName = cursor.getString(cursor
					.getColumnIndex(TBL_Scene.NAME));
			txtName.setText(sceneName);

			// set state image
			final int state = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.STATE));
			if (state == Scene.SCENE_STATE_OFF) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
			} else if (state == Scene.SCENE_STATE_ON) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);

			}

			// state image onclick
			final int sceneID = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene._ID));
			txtName.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (Config.isVibrate)
						new VibrateThread(getActivity().getApplicationContext())
								.start();
					// turn on scene
					mOnControlSceneListener.OnTurnOnScene(sceneID);
					progressDialog = DialogLumi.showProgressDialogLumi(
							mContext, getString(R.string.txt_msg_apply_scene));
				}
			});

			// set schedule
			final int mode = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MODE));
			final int hour = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.HOUR));
			final int minute = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MINUTE));
			if (mode == Scene.SCENE_MODE_AUTO) {
				txvSchedule.setCompoundDrawablesWithIntrinsicBounds(0,
						R.drawable.img_schedule_on, 0, 0);
				txvSchedule.setText(AbstractSceneActivity.padding_str(hour)
						+ ":" + AbstractSceneActivity.padding_str(minute));
			} else if (mode == Scene.SCENE_MODE_NORMAL) {
				txvSchedule.setCompoundDrawablesWithIntrinsicBounds(0,
						R.drawable.img_schedule_off, 0, 0);
				txvSchedule.setText("");
			}

			/*
			 * //config onclick --> edit scene activity
			 * txtName.setOnClickListener(new OnClickListener(){
			 * 
			 * @Override public void onClick(View arg0) { // TODO Auto-generated
			 * method stub Intent intent=new Intent(context,
			 * EditSceneActivity.class);
			 * intent.putExtra(EditSceneActivity.EXTRA_FLOOR_ID, floor_id);
			 * intent.putExtra(EditSceneActivity.EXTRA_ROOM_ID, room_id);
			 * intent.putExtra(EditSceneActivity.EXTRA_SCENE_ID, sceneID);
			 * intent.putExtra(EditSceneActivity.EXTRA_SCENE_NAME, sceneName);
			 * intent.putExtra(EditSceneActivity.EXTRA_SCENE_MODE, mode);
			 * intent.putExtra(EditSceneActivity.EXTRA_SCENE_HOUR, hour);
			 * intent.putExtra(EditSceneActivity.EXTRA_SCENE_MINUTE, minute);
			 * 
			 * Log.d("SceneFragment","edit scene floorID="+floor_id+" room_id="+
			 * room_id+" sceneID="+sceneID+" sceneName="+sceneName
			 * +" mode="+mode+" "+hour+":"+minute);
			 * context.startActivity(intent); }
			 * 
			 * });
			 */

		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
			return View.inflate(context, R.layout.item_listview_scene_active,
					null);
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return false;
		}

	}

	@Override
	public void OnTurnOnScene(int sceneID) {
		// TODO Auto-generated method stub
		// check if scene is turned on
		String selection = new String(TBL_Scene._ID + "=?");
		String[] selectionArgs = new String[] { sceneID + "" };
		String[] projection = new String[] { TBL_Scene.STATE };
		Cursor cursor = getActivity().getContentResolver().query(
				TBL_Scene.CONTENT_URI_SCENE, projection, selection,
				selectionArgs, null);
		if (cursor == null)
			return;
		cursor.moveToFirst();
//		if (cursor.getInt(cursor.getColumnIndex(TBL_Scene.STATE)) == Scene.SCENE_STATE_ON)
//			return;

		// send to content provider
		ContentValues values = new ContentValues();
		values.put(TBL_Scene._ID, sceneID);
		getActivity().getContentResolver().update(
				TBL_Scene.CONTENT_URI_TURNON_SCENE, values, null, null);

		// //set broadcast receiver
		mReceiver = new SceneReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(getActivity().getString(
				R.string.txt_broadcast_turnOn_scene_successful));
		filter.addAction(getActivity().getString(
				R.string.txt_broadcast_turnOn_scene_failed));
		getActivity().registerReceiver(mReceiver, filter);

	}

	@Override
	public void OnTurnOffScene(int sceneID) {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put(TBL_Scene._ID, sceneID);
		getActivity().getContentResolver().update(
				TBL_Scene.CONTENT_URI_TURNOFF_SCENE, values, null, null);
	}

	public class SceneReceiver extends BroadcastReceiver {

		// private ProgressDialog mDialog;

		public SceneReceiver() {
			// mDialog = dialog;
		}
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// mDialog.cancel();
			getActivity().unregisterReceiver(mReceiver);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_turnOn_scene_successful))) {
				DialogLumi.cancelProgressDialogLumi(progressDialog);

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_turnOn_scene_failed))) {
				DialogLumi.cancelProgressDialogLumi(progressDialog);
				DialogLumi.showAlertDialog(context,
						getString(R.string.txt_error),
						getString(R.string.txt_error_cannot_connect_HC));
			}
		}
	}
}
